using System;
using System.Collections.Generic;
using System.Text;
using WP.DB;
using System.Data;
namespace WP.Commons
{
    public class Permission
    {
        /// <summary>
        /// Get SQL where condiont by program name
        /// </summary>
        /// <param name="bNeedWhereWord"></param>
        /// <param name="strProgName"></param>
        /// <returns></returns>

        public static string GetSubCondition()
        {
            return GetSubCondition(false, "", SysVar.CurrentMenuInfo.iParameter);
        }

        public static string GetSubCondition(bool bNeedWhereWord)
        {
            return GetSubCondition(bNeedWhereWord, "", SysVar.CurrentMenuInfo.iParameter);
        }
        public static string GetSubCondition(string strProgOrTableName)
        {
            return GetSubCondition(false , strProgOrTableName,SysVar.CurrentMenuInfo.iParameter);
        }
        public static string GetSubCondition(bool bNeedWhereWord, string strProgOrTableName,int iParameter)
        {
            bool bSpecialSwitch = false, bAllSwitch = false;
            string strReturn = "",strCond="";
            WP.DB.DBAccess dbcon= new WP.DB.DBAccess(false ,false);
  
            if (strProgOrTableName == "")
            {
                strProgOrTableName = SysVar.CurrentMenuInfo.strProgname   ;
            }
            strProgOrTableName = strProgOrTableName.Trim().ToLower();

            switch (strProgOrTableName)
            {
                case "mswitch":
                    #region switch
                    switch (iParameter)
                    {
                         case 1:
                              strReturn=  " Upper(Ltrim(Rtrim(SwitchSys)))='GL'";
                            break ;
                        case 2:
                              strReturn= " Upper(Ltrim(Rtrim(SwitchSys)))='AP'";
                             break ;
                        case 3:
                              strReturn= " Upper(Ltrim(Rtrim(SwitchSys)))='AR'";
                             break ;
                        case 4:
                              strReturn= " Upper(Ltrim(Rtrim(SwitchSys)))='OE'";
                            break ;
                        case 5:
                              strReturn= " Upper(Ltrim(Rtrim(SwitchSys)))='IM'";
                             break ;
                        case 6:
                              strReturn= " Upper(Ltrim(Rtrim(SwitchSys)))='PO'";
                             break ;
                        case 7:
                              strReturn= " Upper(Ltrim(Rtrim(SwitchSys)))='RM'";
                             break ;
                        case 8:
                              strReturn= " Upper(Ltrim(Rtrim(SwitchSys)))='M'";
                             break ;
                        case 9:
                              strReturn= " Upper(Ltrim(Rtrim(SwitchSys)))='TP'";
                             break ;
                        case 99:   //        'All Switch
                              strReturn= "";

                              bAllSwitch = true;
                             break ;
                        default :
                            strReturn= "";
                            bSpecialSwitch = true;
                            break ;
                         
                    }

                    if (strReturn != "")
                    {
                        strReturn = strReturn + " and ";
                    }
                   
                     if( bSpecialSwitch )
                     {
                        strReturn = strReturn + " InSwitchMaint = 1 and SpecialSwitch=1 ";
                     }
                     else
                     {
                        if( bAllSwitch )
                            strReturn = strReturn + "InSwitchMaint = 1 and SpecialSwitch<>1" ;
                        else
                            strReturn = strReturn + " InSwitchMaint = 1 and SpecialSwitch<>1" ;
                      }
                     
                    #endregion
                      break;
                case "mmiscswitch":
                    #region mmiscswitch
                    switch (iParameter)
                    {
                        case 1:
                            strReturn = " Upper(Ltrim(Rtrim(SystemName)))='GL'";
                            break;
                        case 2:
                            strReturn = " Upper(Ltrim(Rtrim(SystemName)))='AP'";
                            break;
                        case 3:
                            strReturn = " Upper(Ltrim(Rtrim(SystemName)))='AR'";
                            break;
                        case 4:
                            strReturn = " Upper(Ltrim(Rtrim(SystemName)))='OE'";
                            break;
                        case 5:
                            strReturn = " Upper(Ltrim(Rtrim(SystemName)))='IM'";
                            break;
                        case 6:
                            strReturn = " Upper(Ltrim(Rtrim(SystemName)))='PO'";
                            break;
                        case 7:
                            strReturn = " Upper(Ltrim(Rtrim(SystemName)))='RM'";
                            break;
                        case 8:
                            strReturn = " Upper(Ltrim(Rtrim(SystemName)))='M'";
                            break;
                        case 9:
                            strReturn = " Upper(Ltrim(Rtrim(SystemName)))='TP'";
                            break;
                        case 99:   //        'All Switch
                            strReturn = "";

                            bAllSwitch = true;
                            break;
                        default:
                            strReturn = "";
                            bSpecialSwitch = true;
                            break;

                    }
                    if (strReturn != "")
                    {
                        strReturn = strReturn + " and ";
                    }

                    if (bSpecialSwitch)
                    {
                        strReturn = strReturn + " InSwitchMaint = 1 and SpecialSwitch=1 ";
                    }
                    else
                    {
                        if (bAllSwitch)
                            strReturn = strReturn + " InSwitchMaint = 1 and SpecialSwitch<>1";
                        else
                            strReturn = strReturn + " InSwitchMaint = 1 and SpecialSwitch<>1";
                    }
                    #endregion
                    break;
                case "frmarcustomermtn":
                    strReturn = GetPermitArCustCond();
                    break;
                case "frmoebidmastermtn":
                    strReturn = GetPermitBidCond();
                    break;
                case "frmoebidjobcontrolhdrmtn":
                    strReturn = GetPermitJobCond();
                    break;
                case "frmpoorderhdrmtn":
                     strReturn = GetPermitPoCond();
                     if (iParameter == 0)   //outstand po
                     {
                         strReturn = strReturn + (strReturn == "" ? "IsQuote =0 and IsInterCmp=0 and Posted=0 and Void=0 and isReturnVoid=0 and IsReturn=0  and IsPrepaid=0 " : " and IsInterCmp=0 and IsQuote =0 and Posted=0 and Void=0 and isReturnVoid=0 and IsReturn=0 and IsPrepaid=0 ");
                         strReturn = strReturn + " and TwoStepsGoodsRecv=0";
                     }
                     else if (iParameter == 1)   //goods recv po
                     {
                         strReturn = strReturn + (strReturn == "" ? "IsQuote =0 and IsInterCmp=0 and Posted=0 and Void=0 and isReturnVoid=0 and IsBackToBack=0 and IsReturn=0 and IsPrepaid=0 " : " and IsInterCmp=0 and IsQuote =0 and Posted=0 and Void=0 and isReturnVoid=0 and IsBackToBack=0 and IsReturn=0 and IsPrepaid=0 ");
                         strReturn = strReturn + " and TwoStepsGoodsRecv=0";
                     }
                     else if (iParameter == 2)   // po return
                     {
                         strReturn = strReturn + (strReturn == "" ? "IsQuote =0 and IsBackToBack=0 and IsInterCmp=0 and Posted=0 and Void=0 and isReturnVoid=0 and IsReturn=1 and IsPrepaid=0 " : " and IsInterCmp=0 and IsQuote =0 and Posted=0 and Void=0 and isReturnVoid=0 and IsBackToBack=0 and IsReturn=1 and IsPrepaid=0 ");
                         strReturn = strReturn + " and TwoStepsGoodsRecv=0";
                     }
                     else if (iParameter == 3)   //quote po
                     {
                         strReturn = strReturn + (strReturn == "" ? "IsQuote =1 and IsInterCmp=0 and Posted=0 and Void=0 and isReturnVoid=0 and IsReturn=0  and IsPrepaid=0 " : " and IsInterCmp=0 and IsQuote =1 and posted=0 and Void=0 and isReturnVoid=0 and IsReturn=0 and IsPrepaid=0 ");
                         strReturn = strReturn + " and TwoStepsGoodsRecv=0";
                     }
                     else if (iParameter == 10)   //Prepaid Purchase Order 
                     {


                         strReturn = strReturn + (strReturn == "" ? " " : " and ") + "IsQuote =0 and IsInterCmp=0 and Posted=0 and Void=0 and isReturnVoid=0 and IsBackToBack=0 and IsReturn=0 and not exists (select a.ordno from poorderdtl a inner join mlocation b on a.locno=b.locationno and b.directonly=1 and (not (b.VmiType='S' and b.VmiLocation=1)) where a.ordno=poorderhdr.ordno ) ";
                         strReturn = strReturn + " and TwoStepsGoodsRecv=0";
                     }
                     else if (iParameter == 11)   //Prepaid goods recv po
                     {
                         strReturn = strReturn + (strReturn == "" ? " " : " and ") + "IsQuote =0 and IsInterCmp=0 and Posted=0 and Void=0 and isReturnVoid=0 and IsBackToBack=0 and IsReturn=0 and IsPrepaid=1";
                         strReturn = strReturn + " and TwoStepsGoodsRecv=0";
                     }
                     else if (iParameter == 91)   //1 step goods recv po
                     {
                         strReturn = strReturn + (strReturn == "" ? "IsQuote =0 and IsInterCmp=0 and Posted=0 and Void=0 and isReturnVoid=0 and IsBackToBack=0 and IsReturn=0 and IsPrepaid=0 " : " and IsInterCmp=0 and IsQuote =0 and Posted=0 and Void=0 and isReturnVoid=0 and IsBackToBack=0 and IsReturn=0 and IsPrepaid=0 ");
                         strReturn = strReturn + " and TwoStepsGoodsRecv<=1";
                     }
                     else if (iParameter == 92)   //2 step goods recv po
                     {
                         strReturn = strReturn + (strReturn == "" ? "IsQuote =0 and IsInterCmp=0 and Posted=0 and Void=0 and isReturnVoid=0 and IsBackToBack=0 and IsReturn=0 and IsPrepaid=0 " : " and IsInterCmp=0 and IsQuote =0 and Posted=0 and Void=0 and isReturnVoid=0 and IsBackToBack=0 and IsReturn=0 and IsPrepaid=0 ");
                         strReturn = strReturn + " and TwoStepsGoodsRecv=2";
                     }
                     break;
                case "frmoeorderhdrmtn":
                    ////Sales Order Maintenance/ for salesperson    1/7
                    ////Confirm Printed Sales Order to Invoice		2
                    ////Invoice Maintenance		                    3
                    ////Change Sales Order Terms Maintenance		4
                    ////Change Sales Order Status		            5
                    ////Release Order/Invoice from Hold		        6
                    strReturn = GetPermitOECond(dbcon,false ,"",true  ,false ,true );
                    if (iParameter == 1 || iParameter == 7)
                    {
                        if (DataFunctions.GetmSwitchValue(dbcon, "AbleToConfirmAllOrders", "oe") || double.Parse(BaseFunctions.FormatNumeric(DataFunctions.GetmMiscValue(dbcon, "DefOrderStatus", "OE"), "n.0")) == 2)
                            strReturn = " (OrdStatus=20 or OrdStatus=30) " + (strReturn != "" ? " and " + strReturn : "");
                        else
                            strReturn = " (OrdStatus=20) " + (strReturn != "" ? " and " + strReturn : "");
                    }
                    else if (iParameter == 2)
                    {
                        if (DataFunctions.GetmSwitchValue(dbcon, "AbleToConfirmAllOrders", "oe"))
                            strReturn = " (OrdStatus=20 or OrdStatus=30) " + (strReturn != "" ? " and " + strReturn : "");
                        else
                            strReturn = " (OrdStatus=30) " + (strReturn != "" ? " and " + strReturn : "");
                    }
                    else if (iParameter == 3)
                    {
                        if (double.Parse(BaseFunctions.FormatNumeric(DataFunctions.GetmMiscValue(dbcon, "DefInvoiceStatus", "OE"), "n.0")) == 2)
                            strReturn = " (OrdStatus=50 or OrdStatus=60) " + (strReturn != "" ? " and " + strReturn : "");
                        else
                            strReturn = " (OrdStatus=50) " + (strReturn != "" ? " and " + strReturn : "");
                    }
                    else if (iParameter == 5)
                    {
                        strReturn = " (OrdStatus<>10) " + (strReturn != "" ? " and " + strReturn : "");
                    }
                    else if (iParameter == 6)
                    {
                        strReturn = " (OrdStatus=10) " + (strReturn != "" ? " and " + strReturn : "");
                    }
                    else if (iParameter == 8)//cash sale
                    {
                        strReturn = " (ordtype=2 or ordtype=3) " + (strReturn != "" ? " and " + strReturn : "");
                    }
                    break;
                case "frmoequotehdrmtn":
                    strReturn = GetPermitOEQuoteCond(dbcon);
                    break;
                case "frmoequotequickmtn":
                    strReturn = GetPermitOEQuoteCond(dbcon);
                    break;
                case "frmapaccrupayablemtn":
                    strReturn = GetPermitAccruedPayable(iParameter);
                    break;
                case "frmapmchqmtn":
                case "frmapcomputercheckmtn":
                    strReturn = GetPermitAPCheck();
                    break;
                case "frmapsupplierinvmtn":
                    strReturn = GetPermitApSupInvCond();
                    break;
                case "frmarcashrecemtn":
                    strReturn = "CustNo in (select CustNo from arCustomer where branchNo in (select BranchNo from mUserBranch where Access=1 and username='" + SysVar.UserName + "'))";
                    if (DataFunctions.GetmSwitchValue("AccessSelfCashReceipts", "AR"))
                    {
                        strReturn += "and EnterBy='" + SysVar.UserName + "'";
                    }
                    break;
                case "frmapagedpayablerpt":
                    if (iParameter == 1)
                    {
                        strReturn = " UserName = '' and RptGrp = 'AP'";
                    }
                    else
                    {
                        strReturn = " UserName = '" + SysVar.UserName + "' and RptGrp = 'AP'";
                    }
                    //strReturn = " RptGrp = 'AP'";
                    break;
                case "frmaragedrecerpt":
                    if (iParameter == 1)
                    {
                        strReturn = " UserName = '' and RptGrp = 'AR'";
                    }
                    else
                    {
                        strReturn = " UserName = '" + SysVar.UserName + "' and RptGrp = 'AR'";
                    }
                    break;
                case "frmaprankrpt":
                    //strReturn = " UserName = '" + SysVar.UserName + "' and RptGrp = 'RR'";
                    break;
                case "frmarrankrpt":
                    strReturn = " UserName = '" + SysVar.UserName + "' and RptGrp = 'RR'";
                    break;
                default:
                    break;
            }
            dbcon.CloseCon(); 
            if(bNeedWhereWord && strReturn!="")
                strReturn =" where " + strReturn;
            else if(strReturn !="")
                strReturn =" and " + strReturn ;
            return strReturn;
        }

        #region GetPermitOECond: get condition cause for permit user access salse order
        public static string GetPermitOECond(WP.DB.DBAccess dBAccess, bool bIsCreateSalesOrder, string strFieldName, bool bAccessAllSalesOrder, bool bForSalesReturn)
        {
            return  GetPermitOECond(  dBAccess,   bIsCreateSalesOrder,   strFieldName,   bAccessAllSalesOrder,   bForSalesReturn,false );
        
        }
        public static string GetPermitOECond(WP.DB.DBAccess dBAccess, bool bIsCreateSalesOrder, string strFieldName, bool bAccessAllSalesOrder, bool bForSalesReturn ,bool blnForSalesOrder)
        {
            string getPermitOECond = "";

            if (DataFunctions.GetmSwitchValue(dBAccess, "AccessOEByLocBranch", "OE"))
            {
                if (blnForSalesOrder) getPermitOECond = "OeOrderhdr.LocBranchNo in (select BranchNo from muserBranch where Access=1 and username='" + SysVar.UserName + "')";
            }
            if (bAccessAllSalesOrder)
            {
                if (DataFunctions.GetFieldValue(dBAccess, "mUser", "AccessAllSalesOrder", "Username='" + SysVar.UserName + "'") == "True")
                {
                    return getPermitOECond;
                }
            }
            if (DataFunctions.GetmSwitchValue(dBAccess, "AccessSelfSalesOrder", "OE") == false)
            {
                return getPermitOECond;
            }
            if (bIsCreateSalesOrder)
            {
                 getPermitOECond = getPermitOECond + (getPermitOECond != "" ? " and " : "") + " Access=1 and username='" + SysVar.UserName + "'";
            }
            else if (strFieldName == "")
            {
                if (!bForSalesReturn)
                    getPermitOECond = getPermitOECond + (getPermitOECond != "" ? " and " : "") + " OeOrderhdr.SlpNo1 in (select SlspNo from muserTrader where Access=1 and username='" + SysVar.UserName + "')";
                else
                    getPermitOECond = getPermitOECond + (getPermitOECond != "" ? " and " : "") + " OeReturnHdr.SlpNo1 in (select SlspNo from muserTrader where Access=1 and username='" + SysVar.UserName + "')";
            }
            else
            {
                getPermitOECond = getPermitOECond + (getPermitOECond != "" ? " and " : "") + strFieldName + " in (select SlspNo from muserTrader where Access=1 and username='" + SysVar.UserName + "')";
            }

            return getPermitOECond;
        }

        public static string GetPermitOECond(WP.DB.DBAccess dBAccess, bool bIsCreateSalesOrder, string strFieldName, bool bAccessAllSalesOrder)
        {
            return GetPermitOECond(dBAccess, bIsCreateSalesOrder, strFieldName, bAccessAllSalesOrder, false);
        }
        public static string GetPermitOECond(WP.DB.DBAccess dBAccess, bool bIsCreateSalesOrder, string strFieldName)
        {
            return GetPermitOECond(dBAccess, bIsCreateSalesOrder, strFieldName, true,false );
        }

        public static string GetPermitOECond(WP.DB.DBAccess dBAccess, bool bIsCreateSalesOrder)
        {
            return GetPermitOECond(dBAccess, bIsCreateSalesOrder, "", true,false );
        }

        public static string GetPermitOECond(WP.DB.DBAccess dBAccess)
        {
            return GetPermitOECond(dBAccess, false, "", true,false );
        }

        public static string GetPermitOECond(bool bIsCreateSalesOrder)
        {
            string strCond = "";
            WP.DB.DBAccess dbcon = new WP.DB.DBAccess(false, false);
            strCond = GetPermitOECond(dbcon, bIsCreateSalesOrder, "", true,false );
            dbcon.CloseCon();
            return strCond;
        }
        #endregion

        #region GetPermitBidCond
        public static string GetPermitBidCond()
        {
            DBAccess dbcon = new DBAccess(false, false);
            string strReturn = GetPermitBidCond(dbcon,false,"");
            dbcon.CloseCon();
            return strReturn;
        }
        public static string GetPermitBidCond(DBAccess dbcon,bool blnIsCreateSalesOrder,string strFieldName)
        {
            string strCondition = "";
            if (CvtFunc.ToBoolean( DataFunctions.GetFieldValue("mUser", "ViewAllBidJob", "Username='" + SysVar.UserName + "'") ))
            {
                return strCondition;
            }
            if (blnIsCreateSalesOrder)
            {
                strCondition = " BidAccess=1 and username='" + SysVar.UserName + "'";
            }
            else
            {
                strCondition =(strFieldName.Equals(string.Empty)?"SalesRep":strFieldName) +"  in (select SlspNo from muserBid where BidAccess=1 and username='" + SysVar.UserName + "')";
            }
            return strCondition;
        }
        #endregion GetPermitBidCond

        #region GetPermitJobCond
        public static string GetPermitJobCond()
        {
            DBAccess dbcon = new DBAccess(false, false);
            string strReturn = GetPermitJobCond(dbcon, false, "");
            dbcon.CloseCon();
            return strReturn;
        }
        public static string GetPermitJobCond(DBAccess dbcon, bool blnIsCreateSalesOrder, string strFieldName)
        {
            string strCondition = "";
            if (CvtFunc.ToBoolean(DataFunctions.GetFieldValue("mUser", "ViewAllBidJob", "Username='" + SysVar.UserName + "'")))
            {
                return strCondition;
            }
            if (blnIsCreateSalesOrder)
            {
                strCondition = " JobAccess=1 and username='" + SysVar.UserName + "'";
            }
            else
            {
                if(strFieldName.Equals(string.Empty))
                {
                    strCondition = "JobNo in (select jobno from oebidjobcontrolgeneral where SlspNo_shipto in (select SlspNo from muserBid where JobAccess=1 and username='" + SysVar.UserName + "'))";
                }
                else
                {
                    strCondition = strFieldName + " in (select SlspNo from muserBid where JobAccess=1 and username='" + SysVar.UserName + "')";
                }
                
            }
            return strCondition;
        }
        #endregion GetPermitJobCond

        #region GetPermitOEQuoteCond: get condition cause for permit user access salse order
        public static string GetPermitOEQuoteCond(WP.DB.DBAccess dBAccess, bool bIsCreateSalesOrder, string strFieldName, bool bAccessAllSalesOrder)
        {
            string getPermitOEQuoteCond = "";

            if (DataFunctions.GetmSwitchValue(dBAccess, "AccessCustTransationsByCustBrn", "OE") == false)
            { 
                if (bAccessAllSalesOrder)
                {
                    if (CvtFunc.ToBoolean(DataFunctions.GetFieldValue("mUser", "AccessAllSalesOrder", "Username='" + SysVar.UserName + "'") ) )
                    {
                        return getPermitOEQuoteCond;
                    }
                }
                

                if (DataFunctions.GetmSwitchValue(dBAccess, "AccessSelfOeQuote", "OE") == false)
                {
                    return getPermitOEQuoteCond;
                }
            }
            
           
            if (bIsCreateSalesOrder)
            {
                getPermitOEQuoteCond = " Access=1 and username='" + SysVar.UserName + "'";
            }
            else if (strFieldName == "")
            {
                getPermitOEQuoteCond = " OeQuoteHdr.SlpNo1 in (select SlspNo from muserTrader where Access=1 and username='" + SysVar.UserName + "')";

                 if (DataFunctions.GetmSwitchValue(dBAccess, "AccessCustTransationsByCustBrn", "OE"))
                 {
                     getPermitOEQuoteCond += " and OeQuoteHdr.CustNo in (select CustNo from arCustomer where branchNo in (select BranchNo from mUserBranch where Access=1 and username='" + SysVar.UserName + "'))";
                 }
            }
            else
            {
                getPermitOEQuoteCond = strFieldName + " in (select SlspNo from muserTrader where Access=1 and username='" + SysVar.UserName + "')";
            }
            return getPermitOEQuoteCond;

        }

        public static string GetPermitOEQuoteCond(WP.DB.DBAccess dBAccess, bool bIsCreateSalesOrder, string strFieldName)
        {
            return GetPermitOEQuoteCond(dBAccess, bIsCreateSalesOrder, strFieldName, true);
        }

        public static string GetPermitOEQuoteCond(WP.DB.DBAccess dBAccess, bool bIsCreateSalesOrder)
        {
            return GetPermitOEQuoteCond(dBAccess, bIsCreateSalesOrder, "", true);
        }

        public static string GetPermitOEQuoteCond(WP.DB.DBAccess dBAccess)
        {
            return GetPermitOEQuoteCond(dBAccess, false, "", true);
        }

        public static string GetPermitOEQuoteCond(bool bIsCreateSalesOrder)
        {
            string strCond = "";
            WP.DB.DBAccess dbcon = new WP.DB.DBAccess(false, false);
            strCond = GetPermitOEQuoteCond(dbcon, bIsCreateSalesOrder, "", true);
            dbcon.CloseCon();
            return strCond;
        }
        #endregion

        public static string GetPermitPoCond()
        {
            string strCond = string.Empty;
            WP.DB.DBAccess dbcon = new WP.DB.DBAccess(false, false);
            strCond = GetPermitPoCond(dbcon, false, "");
            dbcon.CloseCon();
            return strCond;
        }
        public static string GetPermitPoCond(bool bIsCreateSalesOrder)
        {
            string strCond = string.Empty;
            WP.DB.DBAccess dbcon = new WP.DB.DBAccess(false, false);
            strCond = GetPermitPoCond(dbcon, bIsCreateSalesOrder, "");
            dbcon.CloseCon();
            return strCond;
        }
        public static string GetPermitPoCond(string strFieldName)
        {
            string strCond = string.Empty;
            WP.DB.DBAccess dbcon = new WP.DB.DBAccess(false, false);
            strCond = GetPermitPoCond(dbcon, false, strFieldName);
            dbcon.CloseCon();
            return strCond;
        }
        public static string GetPermitPoCond(bool bIsCreateSalesOrder, string strFieldName)
        {
            string strCond = string.Empty;
            WP.DB.DBAccess dbcon = new WP.DB.DBAccess(false, false);
            strCond = GetPermitPoCond(dbcon, bIsCreateSalesOrder, strFieldName);
            dbcon.CloseCon();
            return strCond;
        }
        public static string GetPermitPoCond(DBAccess dbcon, bool bIsCreateSalesOrder, string strFieldName)
        {
            string strCond = "";
            if (strFieldName == "")
            {
                if (DataFunctions.GetmSwitchValue(dbcon,"AccessPOByUserBranch", "PO"))
                {
                    if(DataFunctions.GetmSwitchValue(dbcon,"AccessPOByLocBranch", "PO"))
                        strCond = "POOrderhdr.LocBranchNo in (select BranchNo from muserBranch where Access=1 and username='" + SysVar.UserName + "')";
                    else 
                        strCond= "POOrderhdr.BranchNo in (select BranchNo from muserBranch where Access=1 and username='" + SysVar.UserName + "')";
                }
            }

            if (DataFunctions.GetFieldValue(dbcon, "mUser", "AccessAllSalesOrder", "Username='" + SysVar.UserName + "'") == "True")
            {
                return strCond;
            }

            if (DataFunctions.GetmSwitchValue(dbcon, "AccessSelfPurchaseOrder", "PO") ==false )
            {
                return strCond;
            }

            if (bIsCreateSalesOrder)
            {
                strCond = strCond + (strCond != "" ? " and " : "") + " POAccess=1 and username='" + SysVar.UserName + "'";
            }
            else
            {
                if (strFieldName == "")
                {
                    if(!DataFunctions.GetmSwitchValue( "EnterTraderNo", "PO"))
                        strCond = strCond + (strCond != "" ? " and " : "") + " POOrderhdr.BuyBy in (select SlspNo from muserTrader where POAccess=1 and username='" + SysVar.UserName + "')";
                    else
                         strCond = strCond + (strCond != "" ? " and " : "") + " POOrderhdr.Trader in (select SlspNo from muserTrader where POAccess=1 and username='" + SysVar.UserName + "')";
                }
                else
                {
                    strCond = strFieldName + " in (select SlspNo from muserTrader where POAccess=1 and username='" + SysVar.UserName + "')";
                }
            }
            return strCond ;
        }

        public static string GetMenuSecurity(string MenuId)
        {
            return GetMenuSecurity(MenuId, "");
        }
        public static string GetMenuSecurity(DBAccess dbcon, string MenuId)
        {

            string strReturn = GetMenuSecurity(dbcon, MenuId, "");
            return strReturn;
        }
        public static string GetMenuSecurity(string MenuId, string strTableName)
        {
            DBAccess dbcon=new DBAccess(false ,false );
            string strReturn = GetMenuSecurity(dbcon, MenuId, strTableName);
            dbcon.CloseCon();
            return strReturn;
        }
        public static string GetMenuSecurity(DBAccess dbcon,  string MenuId,string strTableName)
        {

            //mUserMenu
            //OnlyUseUserMenu

            if (MenuId == "000") return "Y";
            if (MenuId.Trim() == "")
            {
                //Add by Z, when there is not mtn menu, use frmedit
                if (DataFunctions.GetFieldValue(dbcon,"mTableDict", "TableName", "TableName='" + strTableName + "' and MtnModuleName='frmEdit'") != "")
                {
                    return "Y";
                }
                else
                {
                    return "N";
                }
            }
            string strPermitLevel = "permit" + string.Format("{0:00}", long.Parse(BaseFunctions.FormatNumeric(DataFunctions.GetFieldValue(dbcon,"mUser", ModuleInfo.SecurityGrp(MenuId)  , "UserName='" + SysVar.UserName + "'"), "n.0")));
            if (strPermitLevel == "permit00") return "N";


            string strPermit = DataFunctions.GetFieldValue(dbcon, "mMenu", strPermitLevel, "MenuId='" + MenuId + "' and ProgStatus='D'").Trim().ToUpper();
            if (strPermit == "") strPermit = "N";
           
            if (strPermit != "N")
            {
                string strParentMenuId=GetParentMenuId(MenuId);
                while( strParentMenuId !="")
                {
                    string strParentPermit = "",strProgStatus="";
                    DataRow drMenu = dbcon.GetDataFirstRow("select top 1 * from mmenu where menuid ='" + strParentMenuId + "'");
                    if (drMenu != null)
                    {
                        strParentPermit=CvtFunc.ToString(drMenu[strPermitLevel]).Trim().ToUpper();
                        strProgStatus = CvtFunc.ToString(drMenu["ProgStatus"]).Trim().ToUpper();
                    }

                    if (strParentPermit == "" || strParentPermit == "N" || strProgStatus == "" || strProgStatus=="F") return "N";
                    strParentMenuId = GetParentMenuId(strParentMenuId);
                }
                
            }
            bool blnOnlyUseUserMenu = CvtFunc.ToBoolean(DataFunctions.GetFieldValue(dbcon, "mUser", "OnlyUseUserMenu", "UserName='" + SysVar.UserName + "'"));    
            if (blnOnlyUseUserMenu)
            {
                string strUserMenuName = DataFunctions.GetFieldValue(dbcon, "MUser", "DefUserMenuName", "UserName='" + SysVar.UserName +"'").TrimEnd() ;
                if (strUserMenuName!="" && !DataFunctions.CheckRecordExist(dbcon, "mUserMenu", MenuId, "MenuID", "UserName='" + SysVar.UserName + "' and UserMenuName='" + strUserMenuName + "'"))
                {
                    return "N";
                }
            }
            return strPermit.Trim().ToUpper()  ; 
        }

        public static string GetParentMenuId(string strMenuId)
        {
            if (strMenuId.Substring(3, 3) != "000" && strMenuId.Substring(6, 6) == "000000") return strMenuId.Substring(0, 3) + "000000000";
            if (strMenuId.Substring(3, 3) != "000" && strMenuId.Substring(6, 3) != "000" && strMenuId.Substring(9, 3) == "000") return strMenuId.Substring(0, 6) + "000000";
            if (strMenuId.Substring(3, 3) != "000" && strMenuId.Substring(6, 3) != "000" && strMenuId.Substring(9, 3) != "000") return strMenuId.Substring(0, 9) + "000";
            return "";
        }

        #region GetPermitOeContactCond: get condition cause for permit user access contact management
        public static string GetPermitOeContactCond(DBAccess dBAccess, bool bIsCreateSalesOrder, string strFieldName)
        {
            string strCondition = "";

            if (dBAccess == null)
            {
                dBAccess = new DBAccess();
            }

            if ( DataFunctions.GetFieldValue(dBAccess, "mUser", "AccessAllSalesOrder", "Username='" + SysVar.UserName + "'") != "Yes")
            {
                if (bIsCreateSalesOrder)
                    strCondition = " Access=1 and username='" + SysVar.UserName + "'";
                else
                {
                    if (strFieldName == "")
                        strCondition = @" OeContactMarketHdr.slspName in 
							(select SlspName from arsalesperson where SlspNo in (select SlspNo from muserTrader where Access=1 and username='" + SysVar.UserName + "'))";
                    else
                        strCondition = strFieldName + @" in 
							(select SlspName from arsalesperson where SlspNo in (select SlspNo from muserTrader where Access=1 and username='" + SysVar.UserName + "'))";
                }
            }

            return strCondition;
        }
        public static string GetPermitOeContactCond(DBAccess dBAccess, bool bIsCreateSalesOrder)
        {
            return GetPermitOeContactCond(dBAccess, bIsCreateSalesOrder, "");
        }

        public static string GetPermitOeContactCond(DBAccess dBAccess)
        {
            return GetPermitOeContactCond(dBAccess, false, "");
        }
        #endregion


        public static string GetPermitArCustCond()
        {
            DBAccess dbcon = new DBAccess(false, false);
            string strReturn = GetPermitArCustCond(dbcon);
            dbcon.CloseCon();
            return strReturn;
        }
        public static string GetPermitArCustCond(DBAccess dbcon)
        {
            string strCondition = "";
            if (DataFunctions.GetmSwitchValue(dbcon, "AccessCustbyCustLocBrn", "AR"))
            {
                strCondition = "  custno in (select custno from arCustomer a inner join mLocation b on a.locationno=b.locationno where b.branchno in (select branchno from mUserBranch where username='" + SysVar.UserName + "' and access=1))";
            }
            string strCond = "";
            if (DataFunctions.GetmSwitchValue(dbcon, "AccessCustbyCustBrn", "AR"))
            {
                strCond = "branchno in (select branchno from mUserBranch where username='" + SysVar.UserName + "' and access=1)";
                strCondition = (strCondition == "" ? strCond : " and " + strCond);
            }
            return strCondition;
        }

        public static string GetPermitAccruedPayable(int iParameter)
        {
            //get condition cause for permit user access ap accruPayable
            string strGetPermitAccruedPayable = string.Empty;
            
            if (DataFunctions.GetmSwitchValue("AccessSelfAccruedPayable", "AP"))
                strGetPermitAccruedPayable = " username ='" + SysVar.UserName + "'";

            if (strGetPermitAccruedPayable.Length > 0)
            {
                strGetPermitAccruedPayable += "and ";
            }
            if (iParameter == 10)
            {
                strGetPermitAccruedPayable += "AccruType=1 ";
            }
            else if (iParameter == 2)
            {
                strGetPermitAccruedPayable += "AccruType=2 ";
            }
            else
            {
                strGetPermitAccruedPayable += "AccruType=0 ";
            }
            return strGetPermitAccruedPayable;
        }

        public static string GetPermitAPCheck()
        {
            //get condition cause for permit user access ap check.
            string strGetPermitAPCheck = string.Empty;

            if (DataFunctions.GetmSwitchValue("AccessSelfCheck", "AP"))
                strGetPermitAPCheck = " Enterby ='" + SysVar.UserName + "'";

            return strGetPermitAPCheck;
        }

        public static string GetPermitApSupInvCond()
        {
            //get condition cause for permit user access ap supplier invoice
            string strGetPermitApSupInvCond = string.Empty;

            if (DataFunctions.GetmSwitchValue("AccessSelfSupInvoice", "AP"))
                strGetPermitApSupInvCond = " Enterby ='" + SysVar.UserName + "'";

            return strGetPermitApSupInvCond;
        }


        public static bool AllowTagAdjust()
        {
            DBAccess db  = new DBAccess(false, false);

            string strSql;

            if (SysVar.CodeSignNo == SysVar.DefineCompany.ForestPlyWood)
            {
                strSql = string.Format("select AllowTagAdjust from mUser where UserName='{0}'", SysVar.UserName);
                DataRow drCheckAccess = db.GetDataFirstRow(strSql);
                if (drCheckAccess == null)
                {
                    return false;
                }
                else
                {
                    if (drCheckAccess["AllowTagAdjust"].ToString().Equals("False"))
                    {
                        return false;

                    }
                }
            }
            return true;
        }
    }

    
//////Private Function GetSubCondition(Optional blnNeedWhereWord As Boolean = True, Optional strProgName As String = "") As String
//////'*************************************
//////'*  Function :Get relative SQL where Cause expression according to parameter of the current menu
//////'*  Return:a SQL where Cause expression
//////'*  author:hzg   01-6-23
//////'***************************************
//////     Dim blnSpecialSwitch As Boolean 'Special Switch
//////     Dim blnAllSwitch As Boolean
//////     Dim clsdata As New clsPublicDataFunction
//////     GetSubCondition = ""
//////     blnSpecialSwitch = False
//////     blnAllSwitch = False
//////     If strProgName = "" Then strProgName = gCurrentMenuInfo.Progname
//////      Select Case Trim(UCase(strProgName))
//////        Case UCase("mSwitch")
//////             Select Case gCurrentMenuInfo.Parameter
//////             Case 1
//////                  GetSubCondition = " Upper(Ltrim(Rtrim(SwitchSys)))='GL'"
//////             Case 2
//////                  GetSubCondition = " Upper(Ltrim(Rtrim(SwitchSys)))='AP'"
//////             Case 3
//////                  GetSubCondition = " Upper(Ltrim(Rtrim(SwitchSys)))='AR'"
//////             Case 4
//////                  GetSubCondition = " Upper(Ltrim(Rtrim(SwitchSys)))='OE'"
//////             Case 5
//////                  GetSubCondition = " Upper(Ltrim(Rtrim(SwitchSys)))='IM'"
//////             Case 6
//////                  GetSubCondition = " Upper(Ltrim(Rtrim(SwitchSys)))='PO'"
//////             Case 7
//////                  GetSubCondition = " Upper(Ltrim(Rtrim(SwitchSys)))='RM'"
//////             Case 8
//////                  GetSubCondition = " Upper(Ltrim(Rtrim(SwitchSys)))='M'"
//////            Case 9
//////                  GetSubCondition = " Upper(Ltrim(Rtrim(SwitchSys)))='TP'"
//////             Case 99        'All Switch
//////                  GetSubCondition = ""
//////                  blnAllSwitch = True
//////             Case gSpecialSwitch
//////                GetSubCondition = ""
//////                blnSpecialSwitch = True
//////             End Select
             
//////             If Len(GetSubCondition) > 0 Then
//////                GetSubCondition = GetSubCondition & " and "
//////             End If
             
//////             If blnSpecialSwitch Then
//////                GetSubCondition = GetSubCondition & " InSwitchMaint = 1 and SpecialSwitch=1 "
//////             Else
//////                If blnAllSwitch Then
//////                    GetSubCondition = GetSubCondition & "InSwitchMaint = 1 and SpecialSwitch<>1" '" InSwitchMaint<>SpecialSwitch "
//////                Else
//////                    GetSubCondition = GetSubCondition & " InSwitchMaint = 1 and SpecialSwitch<>1 "
//////                End If
//////             End If
             
//////        Case UCase("mMiscSwitch")
//////            Select Case gCurrentMenuInfo.Parameter
//////            Case 1
//////                 GetSubCondition = " Upper(Ltrim(Rtrim(SystemName)))='GL'"
//////            Case 2
//////                 GetSubCondition = " Upper(Ltrim(Rtrim(SystemName)))='AP'"
//////            Case 3
//////                 GetSubCondition = " Upper(Ltrim(Rtrim(SystemName)))='AR'"
//////            Case 4
//////                 GetSubCondition = " Upper(Ltrim(Rtrim(SystemName)))='OE'"
//////            Case 5
//////                 GetSubCondition = " Upper(Ltrim(Rtrim(SystemName)))='IM'"
//////            Case 6
//////                 GetSubCondition = " Upper(Ltrim(Rtrim(SystemName)))='PO'"
//////            Case 7
//////                 GetSubCondition = " Upper(Ltrim(Rtrim(SystemName)))='RM'"
//////            Case 8
//////                 GetSubCondition = " Upper(Ltrim(Rtrim(SystemName)))='M'"
//////            Case 99        'All Switch
//////                 GetSubCondition = ""
//////                 blnAllSwitch = True
//////            Case gSpecialSwitch
//////                GetSubCondition = ""
//////                blnSpecialSwitch = True
//////            End Select
            
//////            If Len(GetSubCondition) > 0 Then
//////                GetSubCondition = GetSubCondition & " and "
//////            End If
             
//////            If blnSpecialSwitch Then
//////               GetSubCondition = GetSubCondition & " InSwitchMaint = 1 and SpecialSwitch=1 "
//////            Else
//////                If blnAllSwitch Then
//////                    GetSubCondition = GetSubCondition & " InSwitchMaint = 1 and SpecialSwitch<>1 " '" InSwitchMaint<>SpecialSwitch "
//////                Else
//////                    GetSubCondition = GetSubCondition & " InSwitchMaint = 1 and SpecialSwitch<>1 "
//////                End If
               
//////            End If
//////        Case UCase("frmpoGoodsrecvMtn")
//////             GetSubCondition = "IsBackToBack=0"
//////             If gCurrentMenuInfo.Parameter = 2 Then
//////                GetSubCondition = "IsBackToBack=0 and isReturn=1"
//////             Else
//////                GetSubCondition = "IsBackToBack=0 and IsReturn=0"
//////             End If
//////             Dim strCond As String
//////             strCond = clsdata.GetPermitPOCond()
//////             GetSubCondition = GetSubCondition & IIf(Trim(strCond) = "", "", " and " & strCond)
//////             Set clsdata = Nothing
//////        Case UCase("frmpoBlockBuyOrderMtn")
//////             GetSubCondition = "IsBackToBack=0"
//////             GetSubCondition = GetSubCondition & " and ordno in (select ordno from poOrderDtl where locno in (select locationno from mlocation where directonly=1 and not VmiLocation=1))"
//////             GetSubCondition = GetSubCondition & " and ordno not in (select PoordNo from oeOrderDtl where PoordNo<>'')"

//////             strCond = clsdata.GetPermitPOCond()
//////             GetSubCondition = GetSubCondition & IIf(Trim(strCond) = "", "", " and " & strCond)
//////             Set clsdata = Nothing
//////        Case UCase("frmPoPurchaseOrderMtn"), UCase("frmPoDtlandTrailMtn"), UCase("PoOrderhdr")
//////             GetSubCondition = clsdata.GetPermitPOCond()
//////             GetSubCondition = GetSubCondition & IIf(Trim(GetSubCondition) = "", " IsReturn=0 ", " and IsReturn=0")
//////             Set clsdata = Nothing
//////        Case UCase("frmOEOrderEntryMtn"), UCase("OeOrderhdr")
//////             Dim clsFunc As New clsPublicFunction
//////             GetSubCondition = clsdata.GetPermitOECond()
//////             If gCurrentMenuInfo.Parameter = 1 Then
//////                If GetmSwitchValue("AbleToConfirmAllOrders", "oe") Then
//////                    GetSubCondition = IIf(1 = 1, "(OrdStatus=20 or OrdStatus=30)", "OrdStatus=20") & IIf(Len(GetSubCondition) > 0, " and " & GetSubCondition, "")
//////                Else
//////                    GetSubCondition = IIf(Val(clsFunc.FormatNumeric(GetmMiscValue("DefOrderStatus", "OE"), "n.0")) = 2, "(OrdStatus=20 or OrdStatus=30)", "OrdStatus=20") & IIf(Len(GetSubCondition) > 0, " and " & GetSubCondition, "")
//////                End If
//////             ElseIf gCurrentMenuInfo.Parameter = 3 Then
//////                GetSubCondition = IIf(Val(clsFunc.FormatNumeric(GetmMiscValue("DefInvoiceStatus", "OE"), "n.0")) = 2, "(OrdStatus=50 or OrdStatus=60)", "OrdStatus=50") & IIf(Len(GetSubCondition) > 0, " and " & GetSubCondition, "")
//////             End If
//////             Set clsdata = Nothing
//////             Set clsFunc = Nothing
//////             '......
//////        Case UCase("frmApSupplierInvMtn"), UCase("apSupInvHdr")
//////             GetSubCondition = clsdata.GetPermitApSupInvCond
//////        Case UCase("frmArCashReceMtn"), UCase("arCashHdr")
//////             GetSubCondition = clsdata.GetPermitCashReceiptsCond
//////        Case UCase("apChqHdr"), UCase("frmApMChqMtn"), UCase("frmApComputerCheckMtn")
//////             GetSubCondition = clsdata.GetPermitAPCheck
//////        Case UCase("frmApAccruPayableMtn"), UCase("apAccruInvHdr")
//////             GetSubCondition = clsdata.GetPermitAccruedPayable
             
//////        Case Else
//////             GetSubCondition = ""
//////      End Select
//////      If blnNeedWhereWord And Len(GetSubCondition) > 0 Then
//////         GetSubCondition = " where " & GetSubCondition
//////      ElseIf Len(GetSubCondition) > 0 Then
//////         GetSubCondition = " And " & GetSubCondition
//////      End If
//////End Function

}
